package com.nzd.slsharing.util;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class DateTimeZoneSerializer extends JsonSerializer<LocalDateTime> {
    @Override
    public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        // 将 LocalDateTime 转换为指定时区的 ZonedDateTime
        ZonedDateTime zonedDateTime = value.atZone(ZoneId.of("UTC")) // 将 LocalDateTime 转为 UTC 时区的 ZonedDateTime
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"));  // 转换为目标时区（Asia/Shanghai）

        // 格式化为字符串
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDate = zonedDateTime.format(formatter);

        // 写入 JSON
        gen.writeString(formattedDate);
    }
}
